package cn.harry.modular.sys.controller;

import cn.harry.common.annotation.SysLog;
import cn.harry.common.api.R;
import cn.harry.common.enums.BusinessType;
import cn.harry.modular.sys.domain.SysDict;
import cn.harry.modular.sys.enums.CacheConstants;
import cn.harry.modular.sys.service.SysDictService;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 数据字典
 *
 * @author honghh Date 2020-03-16 09:53:38 Copyright (C) www.tech-harry.cn
 */
@Slf4j
@Tag(name = "sys-dict => 字典管理")
@RestController
@RequiredArgsConstructor
@RequestMapping("sys/dict")
public class SysDictController {

	private final SysDictService sysDictService;

	@Operation(summary = "list 分页列表")
	@Parameters({
			@Parameter(name = "current", description = "当前页", required = true, example = "1"),
			@Parameter(name = "size", description = "每页显示条数", required = true, example = "10")
	})
	@PreAuthorize("@ss.hasPermission('system:dict:list')")
	@GetMapping(value = "/list")
	public R<IPage<SysDict>> list(
			@Parameter(hidden = true)Page<SysDict> page, SysDict sysDict) {
		return R.success(sysDictService.page(page, Wrappers.lambdaQuery(sysDict)));
	}

	/**
	 * 获取字典选择框列表
	 */
	@Operation(summary = "optionSelect 获取字典选择框列表")
	@GetMapping("/optionselect")
	public R<List<SysDict>> optionSelect() {
		return R.success(sysDictService.list());
	}

	@Operation(summary = "{id} 根据id获取详情")
	@PreAuthorize("@ss.hasPermission('system:dict:query')")
	@GetMapping(value = "/{id}")
	public R<SysDict> getById(@PathVariable Long id) {
		return R.success(sysDictService.getById(id));
	}

	@Operation(summary = "新增")
	@PreAuthorize("@ss.hasPermission('system:dict:add')")
	@SysLog(title = "字典数据", businessType = BusinessType.INSERT)
	@PostMapping
	public R create(@RequestBody SysDict sysDict) {
		boolean count = sysDictService.create(sysDict);
		return count ? R.success() : R.failed();
	}

	@Operation(summary = "更新")
	@PreAuthorize("@ss.hasPermission('system:dict:edit')")
	@SysLog(title = "字典数据", businessType = BusinessType.UPDATE)
	@PutMapping
	public R<Integer> update(@RequestBody SysDict sysDict) {
		int count = sysDictService.updateDict(sysDict);
		if (count > 0) {
			return R.success(count);
		}
		return R.failed();
	}

	@Operation(summary = "{ids} 删除字典类型")
	@PreAuthorize("@ss.hasPermission('system:dict:remove')")
	@SysLog(title = "字典类型", businessType = BusinessType.DELETE)
	@DeleteMapping(value = "/{ids}")
	@CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
	public R<Integer> deleteByIds(@Parameter(description = "多个以英文逗号(,)拼接")@PathVariable Long[] ids) {
		return sysDictService.removeBatchByIds(Arrays.asList(ids)) ? R.success()
				: R.failed();
	}

	@Operation(summary = "cache 清除字典缓存")
	@SysLog(title = "清除字典缓存", businessType = BusinessType.DELETE)
	@DeleteMapping("/cache")
	@PreAuthorize("@ss.hasPermission('system:dict:remove')")
	@CacheEvict(value = CacheConstants.DICT_DETAILS, allEntries = true)
	public R clearDictCache() {
		return R.success();
	}


	@Operation(summary = "export 按条件导出（不分页）")
	@SysLog(title = "字典数据", businessType = BusinessType.EXPORT)
	@PreAuthorize("@ss.hasPermission('system:dict:export')")
	@GetMapping("/export")
	public R export(HttpServletResponse response, SysDict sysDict) {
		List<SysDict> list = sysDictService.getExportList(sysDict);
		try {
			EasyExcel.write(response.getOutputStream(), SysDict.class).sheet("字典数据")
					.doWrite(list);
			return R.success();
		}
		catch (IOException e) {
			log.error("字典数据,导出失败 error:{}", e.getMessage());
		}
		return R.failed();
	}

}
